﻿var templateSuccess = '<div><a href="#Create\" > Crear otro </a> <a  href="#Info\"">Volver al listado </a> <label>{0}</label>';

function ViewProjectViewModel(model) {
    var selfModel = this;

    ko.mapping.fromJS(model, {}, selfModel);

    Main.CRUD.PrepareViewModel(selfModel);

    //selfModel.BenefitViewModel = new BenefitViewModel(model.BenefitViewModel);
    //selfModel.BenefitViewModel.List = selfModel.Entity.Benefits;

    //selfModel.TextEditorCreate = new TextEditorViewModel();
    //selfModel.TextEditorCreate.Init("editorContainerCreate", "resultContainerCreate");

    //selfModel.TextEditorUpdate = new TextEditorViewModel();

    selfModel.SelectItem = function (action, item, args) {
        selfModel.SelectedItem(item);

        selfModel.GetHtml(selfModel.SelectedItem().Id(), function () {
            if (action == 'Update') {
                selfModel.TextEditorUpdate.Init("editorContainerUpdate", "resultContainerUpdate");
                selfModel.TextEditorUpdate.EditorObject().setData(selfModel.SelectedItem().Html());
            }
        });

        Main.Page.ChangeHash(action + "/" + item.Id());
    };

    selfModel.Read = function () {
    };


    selfModel.RebindList = function () {
        var method = whoever.AJAX.Method({
            data: {},
            action: "/Project/RebindList"
        });

        method.success(function (List) {
            ko.mapping.fromJS(List, {}, selfModel.List);
        });
    };

    selfModel.UploadPreview = function (e, el) {
        var reader = new FileReader();
        try {
            if (el.target.files.length > 0) {
                reader.onload = function (e) {
                    var input = $(el.target);
                    var preview = $(input).parent().find('.preview');
                    $(preview).attr('src', e.target.result);
                }
                reader.readAsDataURL(el.target.files[0]);
            }
        } catch (e) {

        }

    };

    selfModel.GetHtml = function (id, callBack) {
        var method = whoever.AJAX.Method({
            data: ko.toJSON({ 'id': id }),
            action: "/Project/GetHtml"
        });

        method.success(function (html) {
            if (html)
                selfModel.SelectedItem().Html(html);
            if (callBack)
                callBack();
        });
    };

    selfModel.UploadImage = function (callback) {
        if ($(".create .file")[0].files.length > 0) {
            var image = new FormData();
            image.append("file", $(".create .file")[0].files[0]);

            $.ajax({
                async: true,
                type: 'POST',
                url: '/FileUpload/UploadImage',
                data: { image: image },
                dataType: "json",
                success: function (data) {
                    selfModel.Entity.Image(data.file);
                    callback();
                },
                cache: false,
                contentType: false,
                processData: false
            });
        } else {
            callback();
        }
    };


    selfModel.UpdateImage = function (callback) {
        if ($(".update .file")[0].files.length > 0) {
            var data = new FormData();
            data.append("file", $(".update .file")[0].files[0]);
            data.append("relativePath", viewModel.SelectedItem().Image());

            $.ajax({
                async: true,
                type: 'POST',
                url: '/FileUpload/UpdateImage',
                data: data,
                dataType: "json",
                success: function (data) {
                    viewModel.SelectedItem().Image(data.file);
                    callback();
                },
                error: function (result) {
                    console.log(result);
                },
                cache: false,
                contentType: false,
                processData: false
            });
        } else {
            callback();
        }
    };

    selfModel.Create = function () {
        selfModel.UploadImage(function () {
            selfModel.Entity.Html(selfModel.TextEditorCreate.EditorObject().getData());

            if (Main.Validation.ModelIsValid(selfModel.Entity)) {
                var method = Main.CRUD.Create(selfModel.Entity);

                method.success(function (result) {
                    $.when(ui.Animation.HideLoading()).done(function () {
                        if (result.Success) {
                            ui.Message.Success(result.Message);
                            selfModel.RebindList();
                            whoever.Form.EnableActions();
                        }
                    }
                    );
                });
            }
        });
    };

    selfModel.Update = function () {
        selfModel.UpdateImage(function () {
            selfModel.SelectedItem().Html(selfModel.TextEditorUpdate.EditorObject().getData());

            if (Main.Validation.ModelIsValid(selfModel.SelectedItem())) {
                var method = Main.CRUD.Update(selfModel.SelectedItem());

                method.success(function (result) {
                    ui.Animation.HideLoading();
                    whoever.Form.EnableActions();
                });
            }
        });
    };

    selfModel.Delete = function () {
        if (Main.Validation.ModelIsValid(selfModel.SelectedItem())) {
            var method = Main.CRUD.Delete(selfModel.SelectedItem());

            method.success(function (result) {
                $.when(ui.Animation.HideLoading()).done(function () {
                    if (result.Success) {
                        ui.Message.Success(result.Message);
                        selfModel.RebindList();
                        whoever.Form.EnableActions();
                    }
                }
                );
            });
        }
    };

    Main.CRUD.Init(selfModel, "Info", "Project");
}